package com.zhny.project.shell.impl;

import ch.ethz.ssh2.Connection;
import ch.ethz.ssh2.Session;
import ch.ethz.ssh2.StreamGobbler;
import com.zhny.project.shell.IShellService;
import com.zhny.test.SFTPUtil;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.io.*;

@Service
public class ShellServiceImpl implements IShellService {

    @Value("${remote.host.ip}")
    private String hostIP;
    @Value("${remote.host.user}")
    private String user;
    @Value("${remote.host.password}")
    private String password;
    @Value("${remote.host.port}")
    private int port;
    @Value("${remote.host.resultpath}")
    private String resultpath;
    @Value("${remote.host.shellpath}")
    private String shellpath;

    @Override
    public boolean uploadShellFile(String tmpFilePath, String shellContent, String distDir, String distFileName) throws Exception {
        // 通过string创建shell文件
        File file = new File(tmpFilePath);

        FileWriter writer = new FileWriter(file);
        writer.write(shellContent);
        writer.flush();
        writer.close();

        SFTPUtil sftpUtil = new SFTPUtil(user, password, hostIP, port);

        sftpUtil.login();

        sftpUtil.upload(distDir, distFileName, new FileInputStream(new File(tmpFilePath)));

        sftpUtil.logout();

        Connection conn = new Connection(hostIP);
        conn.connect();
        boolean isAuthenticated = conn.authenticateWithPassword(user, password);

        if (isAuthenticated) {
            Session session = conn.openSession();
            session.execCommand("/usr/bin/chmod u+x " + distDir + "/" + distFileName);

            session.close();
            conn.close();

            return true;
        }

        return false;
    }

    @Override
    public boolean executeShell(String shellFilePath) throws IOException {
        Connection conn = new Connection(hostIP);
        conn.connect();
        boolean isAuthenticated = conn.authenticateWithPassword(user, password);

        if (isAuthenticated) {
            Session session = conn.openSession();
            session.execCommand(shellFilePath);

            session.close();
            conn.close();
            return true;
        }

        return false;
    }

    @Override
    public boolean executeShell(String shellFilePath, String resultFileRemotePath) throws IOException {
        Connection conn = new Connection(hostIP);
        conn.connect();
        boolean isAuthenticated = conn.authenticateWithPassword(user, password);

        if (isAuthenticated) {
            Session session = conn.openSession();
            session.execCommand(shellFilePath);

            InputStream stdout = new StreamGobbler(session.getStdout());
            //返回执行结果
            StringBuffer buffer = new StringBuffer();
            BufferedReader br = new BufferedReader(new InputStreamReader(stdout, "UTF-8"));
            String line = null;

            FileWriter fos = new FileWriter(new File(resultFileRemotePath));

/*            while ((line = br.readLine()) != null) {
                int urlIndex = line.indexOf("tracking URL:");

                if (urlIndex > 0) {
                    String url = line.substring(urlIndex);
                    String applicationId = url.substring(url.indexOf("application"));
                    applicationId = applicationId.substring(0, applicationId.indexOf("/"));

                    System.out.println("applicationId:" + applicationId);
                } else {
                    fos.write(line + "\n");

                    fos.flush();
                    System.out.println(line);
                }

                buffer.append(line + "\n");
            }*/

            session.close();
            conn.close();
            fos.close();

            return true;
        }

        return false;
    }

    @Override
    public void downResultFile(String resultDir, String resultFile, String storeFilePath) {
        SFTPUtil sftpUtil = new SFTPUtil(user, password, hostIP, port);

        sftpUtil.login();

        sftpUtil.download(resultDir, resultFile, storeFilePath);

        sftpUtil.logout();
    }

    @Override
    public String getResultPath(){
        return resultpath;
    }
    @Override
    public String getShellPath(){
        return shellpath;
    }
}
